<template>
  <div style="margin: 20px; margin-top: 60px">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="auto"
      >


        <el-form-item :label="t('searchbar.type')" prop="bdType">
          <el-select
            v-model="queryParams.bdType"
            :placeholder="t('searchbar.typeInfo')"
            clearable
            class="!w-240px"
          >
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.YQ_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>


<!--        <el-form-item :label="t('searchbar.model')" prop="bdMode">
          <el-input
            v-model="queryParams.bdMode"
            :placeholder="t('searchbar.modelInfo')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>-->


<!--        <el-form-item :label="t('searchbar.model')" prop="bdMode">
          <el-select
            v-model="queryParams.bdMode"
            :placeholder="t('searchbar.modelInfo')"
            v-if="getSelectOption"
            clearable
            class="!w-240px"
          >
            <el-option
              v-for="dict in getSelectOption"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>-->


        <el-form-item :label="t('searchbar.model')" prop="bdMode">
        <el-select
          v-model="queryParams.bdMode"
          filterable
          :placeholder="t('searchbar.modelInfo')"
          clearable
          class="!w-240px"
          :remote-method="remoteMethod"
          :loading="stuAllLoading"
          :filter-method="handleChange"
        >
          <el-option
            v-for="item in deviceList"
            :key="item.id"
            :label="item.bdType"
            :value="item.id"
            @click="addForm(item)"
          >
            <span style="float: left">{{ item.mode }}({{ t('searchbar.deviceModeCode') }}:{{ item.deviceModeCode }})</span>
          </el-option>
        </el-select>
      </el-form-item>

        <el-form-item :label="t('searchbar.deviceSiteCode')" prop="deviceSiteCode">
          <el-input
            v-model="queryParams.deviceSiteCode"
            :placeholder="t('searchbar.deviceSiteCodeInfo')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>

        <el-form-item :label="t('searchbar.deviceModeCode')" prop="deviceModeCode">
          <el-input
            v-model="queryParams.deviceModeCode"
            :placeholder="t('searchbar.deviceModeCodeInfo')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>


        <!--      <el-form-item :label="t('searchbar.state')" prop="state">
              <el-select
                v-model="queryParams.state"
                class="!w-240px"
                clearable
                :placeholder="t('searchbar.stateInfo')"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_STATE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>-->

        <!--      <el-form-item :label="t('searchbar.createTime')" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          :start-placeholder="t('searchbar.startDate')"
          :end-placeholder="t('searchbar.endDate')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>-->

        <el-form-item>
          <el-button @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px" /> {{ t('action.search') }}
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" /> {{ t('action.reset') }}
          </el-button>

          <el-button
            type="primary"
            plain
            @click="openForm('create')"
            v-hasPermi="['base:site:create']"
          >
            <Icon icon="ep:plus" class="mr-5px" /> {{ t('action.create') }}
          </el-button>

<!--          <el-button-->
<!--            type="warning"-->
<!--            plain-->
<!--            @click="handleImport"-->
<!--          >-->
<!--            <Icon icon="ep:upload" /> {{ t('action.import') }}-->
<!--          </el-button>-->

<!--          <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          @click="handleExport"-->
<!--          :loading="exportLoading"-->
<!--          v-hasPermi="['base:site:export']"-->
<!--        >-->
<!--          <Icon icon="ep:download" class="mr-5px" /> {{ t('action.export') }}-->
<!--        </el-button>-->

        </el-form-item>
      </el-form>
    </ContentWrap>

    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <!-- 列表 -->
        <ContentWrap>
          <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
            <el-table-column :label="t('searchbar.deviceSiteCode')" align="center" prop="deviceSiteCode" />
            <el-table-column :label="t('searchbar.deviceModeCode')" align="center" prop="deviceModeCode" />
            <el-table-column :label="t('formData.type')" align="center" prop="bdType">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.YQ_TYPE" :value="scope.row.bdType" />
              </template>
            </el-table-column>
            <el-table-column :label="t('formData.factoryCode')" align="center" prop="factoryCode">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.FACTORY_CODE" :value="scope.row.factoryCode" />
              </template>
            </el-table-column>
            <el-table-column :label="t('formData.model')" align="center" prop="bdMode" />

<!--            <el-table-column :label="t('formData.model')" align="center" prop="bdMode">
              <template #default="scope">
                <dict-tag :type="getDictType(scope.row.type)" :value="scope.row.bdMode" />
              </template>
            </el-table-column>-->




            <el-table-column :label="t('formItems.protocol')" align="center" prop="protocol" >
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.XY_TYPE" :value="scope.row.protocol" />
              </template>
            </el-table-column>
            <el-table-column :label="t('formItems.port')" align="center" prop="port" />
            <el-table-column :label="t('formItems.ipAddress')" align="center" prop="ip" />

            <el-table-column :label="t('formData.remark')" align="center" prop="remark" />
            <el-table-column :label="t('formData.state')" align="center" prop="state">
              <template #default="scope">
                <el-tag :type="scope.row.state ? 'success' : 'danger'">
                  {{ scope.row.state ? t('action.start') : t('action.stop') }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column
              :label="t('formData.createTime')"
              align="center"
              prop="createTime"
              :formatter="dateFormatter"
              width="180px"
            />

            <el-table-column
              :label="t('formData.operate')"
              align="center"
              fixed="right"
              width="180px"
            >



              <template #default="scope">

                <el-button
                  v-if="scope.row.state == false"
                  link
                  type="primary"
                  @click="handleStart(scope.row.id)"
                >
                  {{ t('action.start') }}
                </el-button>

                <el-button
                  v-if="scope.row.state == true"
                  link
                  type="danger"
                  @click="handleStop(scope.row.id)"
                >
                  {{ t('action.stop') }}
                </el-button>


                <el-button
                  v-if="scope.row.state == false"
                  link
                  type="primary"
                  @click="openForm('update', scope.row.id)"
                  v-hasPermi="['base:site:update']"
                >
                  {{ t('action.edit') }}
                </el-button>

                <el-button
                  v-if="scope.row.state == false"
                  link
                  type="danger"
                  @click="handleDelete(scope.row.id)"
                  v-hasPermi="['base:site:delete']"
                >
                  {{ t('action.delete') }}
                </el-button>


<!--                <el-button
                  v-if="scope.row.state"
                  link
                  type="danger"
                  @click="handleDisable(scope.row.id)"
                  v-hasPermi="['base:site:update']"
                >
                  {{ t('action.disabled') }}
                </el-button>

                <el-button
                  v-else
                  link
                  type="success"
                  @click="handleEnable(scope.row.id)"
                  v-hasPermi="['base:site:update']"
                >
                  {{ t('action.abled') }}
                </el-button>-->


              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <Pagination
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </ContentWrap>
      </el-col>
    </el-row>
  </div>  
  <!-- 表单弹窗：添加/修改 -->
  <DeviceForm ref="formRef" @success="getList" />
  <DeptSecondForm ref="formSecondRef" @success="getList" />
  <!-- 对象导入模态框 -->
  <ImportForm ref="importFormRef" @success="getList" />

</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import {DeviceApi , DeviceVO} from '@/api/base/device'
import {DeviceBaseApi , DeviceBaseVO} from '@/api/base/devicebase'
import DeviceForm from './DeviceForm.vue'
import { SiteApi, SiteVO } from '@/api/base/site'
import ImportForm from "@/views/base/device/ImportForm.vue";

/** 仪器设备 列表 */
defineOptions({ name: 'Device' })

const stuAllLoading = ref(false)

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const showMenu = ref(false)
const showMenuFL = ref(0)
const loading = ref(true) // 列表的加载中
const list = ref<DeviceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const formSecondRef = ref()
const menuX = ref(0)
const menuY = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceSiteCode: undefined,
  deviceModeCode: undefined,
  name: undefined,
  bdType: undefined,
  bdMode: undefined,
  factoryCode: undefined,
  state: undefined,
  createTime: [],
  protocol: undefined,
  port: undefined,
  ip: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DeviceApi.getDevicePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}


//------------------------开始暂停部分---------------------------
const formData = ref({
  id: undefined,
  deviceSiteCode: undefined,
  deviceModeCode: undefined,
  name: undefined,
  bdType: undefined,
  bdMode: undefined,
  sceneId: undefined,
  factoryCode: undefined,
  remark: undefined,
  state: undefined,
  protocol: undefined,
  port: undefined,
  ip: undefined,
})
/*开始仪器*/
const handleStart = async (id: number) => {
  try {
    // 二次确认
    await message.enableConfirm()
    formData.value = await DeviceApi.getDevice(id)
    const data = formData.value as unknown as DeviceVO
    //发起操作
    await DeviceApi.startDevice(data)
    message.success("仪器已开始")
    // 刷新列表
    await getList()
  }catch {}
}

/*暂停仪器*/
const handleStop = async (id: number) => {
  try {
    // 二次确认
    await message.disableConfirm()
    formData.value = await DeviceApi.getDevice(id)
    const data = formData.value as unknown as DeviceVO
    //发起操作
    await DeviceApi.stopDevice(data)
    message.success("仪器已暂停")
    // 刷新列表
    await getList()
  }catch {}
}


















//---------------------------------------------------




/** 启用按钮操作 */
const handleEnable = async (id: number) => {
  try {
    // 启用的二次确认
    await message.enableConfirm()
    // 发起启用
    await DeviceApi.enableDevice(id)
    message.success(t(t('action.abledSuccess')))
    // 刷新列表
    await getList()
  } catch {}
}

/** 禁用按钮操作 */
const handleDisable = async (id: number) => {
  try {
    // 禁用的二次确认
    await message.disableConfirm()
    // 发起禁用
    await DeviceApi.disableDevice(id)
    message.success(t(t('action.disabledSuccess')))
    // 刷新列表
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DeviceApi.deleteDevice(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DeviceApi.exportDevice(queryParams)
    download.excel(data, 'device.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})

const handleDeptNodeClick = async (row) => {}

const openContextMenu = async (event, row) => {
  closeContextMenu()
  event.preventDefault()
  document.addEventListener('click', foo) // 给整个document添加监听鼠标事件，点击任何位置执行foo方法
  if (row.level == 0) {
    // 设置菜单位置并显示
    menuX.value = event.clientX - 200
    menuY.value = event.clientY - 120
    showMenu.value = true
    showMenuFL.value = 1
  } else if (row.level == 1) {
    // 设置菜单位置并显示
    menuX.value = event.clientX - 200
    menuY.value = event.clientY - 260
    showMenu.value = true
    showMenuFL.value = 2
  }
}
// 取消鼠标监听事件 菜单栏
const foo = () => {
  showMenu.value = false
  showMenuFL.value = 0
  document.removeEventListener('click', foo) // 要及时关掉监听，不关掉的是一个坑，不信你试试，虽然前台显示的时候没有啥毛病，加一个alert你就知道了
}

const closeContextMenu = () => {
  showMenu.value = false
  showMenuFL.value = 0
}
const openSecondForm = (type: string, id?: number) => {
  closeContextMenu()
  formSecondRef.value.open(type, id)
}
/*

/!*-------------------仪器与型号表单关联部分----------------------*!/
const getDictType = (type) => {
  const dictTypes = {
    A: DICT_TYPE.A,
    B: DICT_TYPE.B,
    C: DICT_TYPE.C,
    D: DICT_TYPE.D,
    E: DICT_TYPE.E,
    F: DICT_TYPE.F,
    G: DICT_TYPE.G,
    H: DICT_TYPE.H
  }
  return dictTypes[type] || '' // 返回对应的字典类型，如果不存在则返回空字符串
}
/!*-------------------仪器与型号搜索框关联部分----------------------*!/
// 计算属性，根据 queryParams.type 返回相应的选项列表
const getSelectOption = computed(() => {
  const dictTypes = {
    A: DICT_TYPE.A,
    B: DICT_TYPE.B,
    C: DICT_TYPE.C,
    D: DICT_TYPE.D,
    E: DICT_TYPE.E,
    F: DICT_TYPE.F,
    G: DICT_TYPE.G,
    H: DICT_TYPE.H
  }
  return getStrDictOptions(dictTypes[queryParams.type])
})
*/

/*---------------------------获取仪器型号清单信息------------------------------*/

const deviceList = ref<DeviceBaseVO[]>([])
const deviceParams = reactive({
  bdType: undefined,
  bdMode: undefined,
})
const remoteMethod = async (query) => {
  stuAllLoading.value = true
  deviceList.value = []
  stuAllLoading.value = false


  deviceParams.bdType = queryParams.bdType
  deviceParams.bdMode = query
  deviceList.value= await DeviceBaseApi.getDeviceList(deviceParams)
}
const handleChange = async (query) => {
  deviceList.value=[]

  deviceParams.bdType = queryParams.bdType
  deviceParams.bdMode = query
  deviceList.value = await DeviceBaseApi.getDeviceList(deviceParams)

  queryParams.bdMode = item.value

}
const addForm = (item) => {
  // queryParams.bdType = item.bdType
  queryParams.bdMode = item.mode
  queryParams.deviceModeCode = item.deviceModeCode
}
//-----------------------------------------------------------------


/*------------------------------导入部分-----------------------------------*/
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}
</script>
<style lang="scss">
.context-menu {
  margin: 0;
  padding: 0;
  z-index: 999;
  position: absolute;
  // height: 40px;
  width: 140px;
  position: absolute;
  border-radius: 5px;
  border: 1px solid #ccc;
  background-color: white;

  .menu-item {
    list-style: none;
    line-height: 20px;
    text-align: left;
    margin: 10px 0px;
    padding-left: 10px;
    font-size: 14px;
    color: #606266;
  }
  li:hover {
    background-color: #edf6ff;
    color: #606266;
  }
}
</style>
